var qs = {
    has:function(selector){

    },
    parentHas:function(node, find){
        if(node==null){
            return false;
        }else if(node.nodeName!="body" && node.nodeName==find){
            return true;
        }else if(node.nodeName=="body"){
            return false;
        }else{
            return this.parentHas(node.parentNode, find);
        }
    },
    firstParent:function(node, find){
        if(node.nodeName!="body" && node.nodeName==find){
            return true;
        }else if(node.nodeName=="body"){
            return false;
        }else{
            return this.firstParent(node.parentNode, find);
        }
    }
}
$.fn.getClientRect = function(){
    var left = $(this).offset().left,
    top = $(this).offset().top,
    t_hight = $(this).outerHeight(true),
    t_width = $(this).outerWidth(true);
    return {
        left : left,
        top : top,
        right : left + t_width,
        bottom : top + t_hight
    };
}
//获取控件在整个页面中的真实位置Y
function getRealLocationTop(val, top) {
    if (val[0].nodeName != '#document') {
		if(val.parent()[0].nodeName!='#document'){
			if( val.parent().css('position')!='fixed'){
				top += val.position().top
			}else{
				// top -= val.offset().top;
			}
		}
        top = getRealLocationTop(val.parent(), top)
    }
    return top
}
//获取控件在整个页面中的真实位置X
function getRealLocationLeft(val, left) {
    if (val[0].nodeName != '#document') {
		if(val.parent()[0].nodeName!='#document'){
			if( val.parent().css('position')!='fixed'){
				left += val.position().left
			}else{
				// top -= val.offset().top;
			}
		}  
        left = getRealLocationLeft(val.parent(), left)
    }
    return left
}
//菜单插件模块
var MyModules = (function Manager(){
                var moudules={}; //对象字面量
                var status={}; //对象是否加载
                function define(name,deps,impl){
                    if(!moudules[name]){
                        for(var i=0;i<deps.length;i++){
                            deps[i]=moudules[deps[i]]; 
                        }
                        moudules[name] = impl.apply(impl,deps);
                        status[name]    = true;
                    }
                    return this;  
                }

                function get(name){
                    if(status[name]){
                        if(typeof moudules[name] == "undefined"){
                            return false;                       
                        }
                        return moudules[name];
                    }                    
                }
                function hasDone(name){
                    return typeof(status[name]) !="undefined" && status[name];
                }
                return {
                    define:define,
                    modules:moudules,
                    hasDone:hasDone,
                    status:status,
                    get:get
                };
            })();

//JS对象深度克隆
var deepClone = function (obj) {
    // 先检测是不是数组和Object
    let isArr = Array.isArray(obj)
    let isJson = Object.prototype.toString.call(obj) === '[object Object]'
    if (isArr) {
        // 克隆数组
        let newObj = []
        for (let i = 0; i < obj.length; i++) {
            newObj[i] = deepClone(obj[i])
        }
        return newObj
    } else if (isJson) {
        // 克隆Object
        let newObj = {}
        for (let i in obj) {
            newObj[i] = deepClone(obj[i])
        }
        return newObj
    }
    // 不是引用类型直接返回
    return obj
}

Object.prototype.deepClone = function () {
    return deepClone(this)
}
Object.defineProperty(Object.prototype, 'deepClone', { enumerable: false });

function deepCloneArray(arr) {
  return arr.map(function(item) {
    if (Array.isArray(item)) {
      return deepCloneArray(item);
    } else if (typeof item === 'object' && item !== null) {
      return deepCloneObject(item);
    } else {
      return item;
    }
  });
}
 
function deepCloneObject(obj) {
  var clone = {};
  for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (Array.isArray(obj[key])) {
        clone[key] = deepCloneArray(obj[key]);
      } else if (typeof obj[key] === 'object' && obj[key] !== null) {
        clone[key] = deepCloneObject(obj[key]);
      } else {
        clone[key] = obj[key];
      }
    }
  }
  return clone;
}

//ARRAY轉成OBJECT數據
function arrayToObject(values){
	var object = {};
	for(var x of values){
		object[x['name']] = x['value'];
	}
	return object;
}
function empty(data){
    try{
        if(data==null){
            return true;
        }else if(typeof (data) == "undefined"){
            return true;
        }else if(data == ""){
            return true;
        }else if(data.length==0){
            return true;
        }
        return false;
    }catch(e){
        return true;
    }
    
}
function ajaxPost($, url, data){
    return new Promise((resolve, reject) => {
                $.ajax({
                    url:url,
                    data: data,
                    type: "POST",
                    dataType: "json",
                    success: function(data){
                        resolve(data);
                    },
                    error: function(err){
                        reject(err);
                    }
                })
            });
}


function ajaxGet($, url, data){
    return new Promise((resolve, reject) => {
                $.ajax({
                    url:url,
                    data: data,
                    dataType: 'json',
                    success: function(data){
                        resolve(data);
                    },
                    error: function(err){
                        reject(err);
                    }
                })
            });
}

function buildUrl(url, object){
 
    var storage = window.localStorage;
    
    if(url.indexOf("?") == -1){
        url = url + "?access-token="+storage.getItem("token");
    }else{
        url = url + "&access-token="+storage.getItem("token");
    }
    if(typeof(object) != 'undefined'){
        for(var x in object){
            url = url + "&"+x+"="+object[x];
        }
    }
    return url;
}
function urlBuild(url, object){
    if(typeof(object) != 'undefined'){
        var i =0;
        for(var x in object){
            if(i==0){
                if(url.indexOf("?") == -1){
                    url = url + "?"+x+"="+object[x];
                }else{
                    url = url + "&"+x+"="+object[x];
                }
            }else{
                url = url + "&"+x+"="+object[x];
            }
            i++;
        }
    }
    return url;
}
function getQuery(variable){
    var query = window.location.href.substring(window.location.href.indexOf('?') + 1);
  
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
           var pair = vars[i].split("=");
           if(pair[0] == variable){return pair[1];}
    }
    return(false);
}
function promptUrl($url){
    prompt('', $url);
}

function formatUrl($url){
    if(checkUrl($url)){
        return $url;
    }
    return URL_INFO.url + "/" + $url;
}

function checkUrl($url){
    var str = $url,
    Expression = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/,
    objExp = new RegExp(Expression);
    if(objExp.test(str)== true){
        return true;
    }
    return false;
}

function setCookie(cname,cvalue,exdays){
    exdays = typeof(exdays) == "undefined" ? 1 : exdays;
    var d = new Date();
    d.setTime(d.getTime()+(exdays*24*60*60*1000));
    var expires = "expires="+d.toGMTString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname){
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) 
    {
        var c = ca[i].trim();
        if (c.indexOf(name)==0) return c.substring(name.length,c.length);
    }
    return "";
}
function toJSON(str) {
  try {
    var jsonData = JSON.parse(str);
    return jsonData;
  } catch (e) {
    return false;
  }
}
// 在ajax加载完成后的回调函数中执行以下代码
function ajaxCallback(myTextarea) {
  // 重新初始化tinymce实例，并将其绑定到文本区域的DOM元素上
  tinymce.init({
    selector: '#'+myTextarea,
    plugins: 'code',
    // 其他tinymce的配置项
  });
  
  tinymce.execCommand('mceRemoveEditor', true, myTextarea);
  setTimeout(function(){
        tinymce.execCommand('mceAddEditor', false, myTextarea);
    }, 100);
}
$(document).on("click", "[img-fancybox]", function(){
    $.fancybox.open({
        src  : $(this).attr("href"),
        type : 'iframe',
        opts : {
            'width': 900,
            'height': 600,
            'maxWidth':900,
            'maxHeight':600,
            'iframe' : {
                'css' : {
                    'maxWidth' : '900px',
                    'maxHeight': '600px'
                }
            },
            'type': 'iframe',
            'autoScale': false,
            afterShow : function( instance, current ) {
                console.info( 'done!' );
            }
        }
    });
    return false;
});
$(document).on("click", "[data-toggle='collapse']", function(){
    
    var target = $(this).attr('aria-controls');
    $(this).parents(".wrap-widget").eq(0).find('#'+target).toggleClass("in");
    return false;
});
$(document).on("click", "[data-toggle='tab']", function(){
    $(this).parents("[role='tablist']").eq(0).children().removeClass("active");
    $(this).parent().addClass("active");
    var target = $(this).attr('aria-controls');
    $("#"+target).parent().children().hide();
    $("#"+target).show();
});
// $(document).on("mouseover", "[data-toggle='tooltip']", function(e){
//     try { e.stopPropagation() } catch(e){
//         e.cancelBubble = true;
//     }
//     var title = $(this).data("original-title");
//     var id = $(this).data("id");
//     var top = $(this).offset().top - 40;
//     var left = $(this).offset().left - 125 + $(this).width()/2;
//     title += " "+id; 
//     var shtml = `<div class="tooltip top in" id="${id}" role="tooltip" style="top:${top}px; left:${left}px; position:absolute;"><div class="tooltip-arrow"></div><div class="tooltip-inner">${title}</div></div>`;
//     $('body').append(shtml);
// }).on("mouseleave", "[data-toggle='tooltip']", function(){
//     $('body').children(".tooltip").remove();
// });
var editor_label_timer;
var WarpLabel = {
    hide:function(){
        editor_label_timer = setTimeout(function(){
            $('body').children(".LdgFormItemGroupButton").hide();
        }, 600);
    },
    show:function(id, title, pos){
        var shtml = `<div class="LdgFormItemGroupButton" id="${id}" data-target="${id}" style="top:${pos.top}px; left:${pos.left}px; position:absolute;"><i class="iconfont icon-move controlMove"></i><i class="iconfont icon-edit controlEdit"></i><i class="iconfont icon-del controlDelete"></i><span class="label label-primary">${title}</span></div>`;
        if($('body').children(".LdgFormItemGroupButton").length>0){
            $('body').children(".LdgFormItemGroupButton").eq(0).prop('outerHTML',shtml);
        }else{
            $('body').append(shtml);
        }
    },
    cleanTimer:function(){
        if(editor_label_timer){
            clearTimeout(editor_label_timer);
            editor_label_timer = null;
        }
    }
};
$(document).on("mouseenter", ".wrap-widget", function(e){
    try { e.stopPropagation() } catch(e){
        e.cancelBubble = true;
    }
    WarpLabel.cleanTimer();
    var title = $(this).data("original-title");
    var id = $(this).data("id");
    var top = $(this).offset().top;
    var left = $(this).offset().left;
    title = title ? title : id;
    WarpLabel.show(id,title, {top:top,left:left});
}).on("mouseout", ".wrap-widget", function(){
    WarpLabel.hide();
});
var is_label_over = false;
$(document).on("mouseenter", ".LdgFormItemGroupButton", function(){
    WarpLabel.cleanTimer();
    is_label_over = true;
}).on("mouseout", ".wrap-widget", function(){
    if(is_label_over){
        WarpLabel.hide();
        is_label_over = false;
    }
});